package 极客算法训练营.chapter09;

import java.util.ArrayList;
import java.util.List;

public class 括号生成 {
    class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> ans = new ArrayList<>();
            dfs(0, n, 0, 0, new StringBuilder(), ans);
            return ans;
        }

        public void dfs(int depth, int n, int left, int right, StringBuilder path, List<String> ans) {
            if (depth == n * 2) {
                ans.add(path.toString());
                return;
            }
            if (left < n) {
                path.append("(");
                dfs(depth + 1, n, left + 1, right, path, ans);
                path.deleteCharAt(path.length() - 1);
            }
            if (right < left) {
                path.append(")");
                dfs(depth + 1, n, left, right + 1, path, ans);
                path.deleteCharAt(path.length() - 1);
            }
        }
    }
}
